<?php

namespace Wantuch\SurveyBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Wantuch\SurveyBundle\Entity\Product;
use Wantuch\SurveyBundle\Entity\Survey;
use Wantuch\SurveyBundle\Entity\Result;
use Wantuch\SurveyBundle\Entity\Comparison;
use Wantuch\SurveyBundle\Form\ProductType;

/**
 * Product controller.
 *
 */
class ProductController extends Controller
{

    /**
     * Lists all Product entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('WantuchSurveyBundle:Product')->findAll();

        return $this->render('WantuchSurveyBundle:Product:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    /**
     * Creates a new Product entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new Product();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $survey=$entity->getSurvey();
            
            $pairs=$this->makePairsArray($survey);
            $survey->setPairs(serialize($pairs));
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('product_show', array('id' => $entity->getId())));
        }

        return $this->render('WantuchSurveyBundle:Product:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a Product entity.
     *
     * @param Product $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Product $entity)
    {
        $form = $this->createForm(new ProductType(), $entity, array(
            'action' => $this->generateUrl('product_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Product entity.
     *
     */
    public function newAction()
    {
        $entity = new Product();
        $form   = $this->createCreateForm($entity);

        return $this->render('WantuchSurveyBundle:Product:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Product entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('WantuchSurveyBundle:Product')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Product entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('WantuchSurveyBundle:Product:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Product entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('WantuchSurveyBundle:Product')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Product entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('WantuchSurveyBundle:Product:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a Product entity.
    *
    * @param Product $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Product $entity)
    {
        $form = $this->createForm(new ProductType(), $entity, array(
            'action' => $this->generateUrl('product_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Product entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('WantuchSurveyBundle:Product')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Product entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('product_edit', array('id' => $id)));
        }

        return $this->render('WantuchSurveyBundle:Product:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a Product entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('WantuchSurveyBundle:Product')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Product entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('product'));
    }

    /**
     * Creates a form to delete a Product entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('product_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
    
    
    public function testMatrixAction($count){
        $possibleValues=array(1/9,1/6,1/3,1,3,6,9);
        $testMatrix=array();
        for($i=0; $i<$count; $i++){
            $testMatrix[$i][$i]=1;
            for($j=$i+1; $j<$count; $j++){
                $testMatrix[$i][$j]=$possibleValues[rand(0,6)];
                $testMatrix[$j][$i]=1/$testMatrix[$i][$j];
            }
        }
        $pierwiastki=array();
        
        for($i=0; $i<$count; $i++){
            $pierwiastki[$i]['produkt']=$i;
            $pierwiastki[$i]['iloczyn']=1;
            
            for($j=0; $j<$count; $j++){
                $pierwiastki[$i]['iloczyn']=$pierwiastki[$i]['iloczyn']*$testMatrix[$i][$j];
            }
            $pierwiastki[$i]['pierwiastek']=pow($pierwiastki[$i]['iloczyn'],1/$count);
            
        }
        
        return new Response('<pre>' . print_r($testMatrix, true) . '</pre><pre>' . print_r($pierwiastki,true).'</pre>');
    }
    
    public function makePairsAction($survey_id){
        $em = $this->getDoctrine()->getManager();

        $survey = $em->getRepository('WantuchSurveyBundle:Survey')->find($survey_id);
        
        $pairs = array();
        
        $products=$survey->getProducts();
        $productsCount=count($products);
        
        for($i=0; $i<$productsCount; $i++){
            for($j=$i+1; $j<$productsCount; $j++){
                $pair=array();
                $zero=0;
                $jeden=1;
                //$random=rand(0,1);
                //if($random==0){
                    //$pair[$zero]=$products[$i];
                    //$pair[$jeden]=$products[$j];
                    $pair[$zero]=$i;
                    $pair[$jeden]=$j;
                //}else{
                    //$pair[$zero]=$j;
                    //$pair[$jeden]=$i;
                //}
                
                shuffle($pair);
                $pairs[]=$pair;
            }
            
        }
       
        shuffle($pairs);
        
        $serializedArray= serialize($pairs); #serializacja tablicy
        $unserializedArray= unserialize("a:6:{i:0;a:2:{i:0;i:1;i:1;i:0;}i:1;a:2:{i:0;i:3;i:1;i:2;}i:2;a:2:{i:0;i:1;i:1;i:3;}i:3;a:2:{i:0;i:2;i:1;i:1;}i:4;a:2:{i:0;i:3;i:1;i:0;}i:5;a:2:{i:0;i:0;i:1;i:2;}}");
        $chosen=$unserializedArray[1][0];
    return new Response('<pre>' . print_r($pairs, true) . '</pre>');
        //return $pairs;
    }
    
    public function calculateOverallSurveyMatrix($survey_id){
        $em = $this->getDoctrine()->getManager();

        $survey = $em->getRepository('WantuchSurveyBundle:Survey')->find($survey_id);
        
        $results=array();
        
        foreach($survey->getResults() as $result){
            $results[]=  unserialize($result->getResultArray()); // rezultaty z każdej ankiety wypelnionej przez uczestnikow
        }
        
        $matrix=array(); //tutaj bedzie macierz globalna produktow
        
        for($j=0;$j<count($survey->getProducts());$j++){
            for($k=0;$k<count($survey->getProducts());$k++){
                $matrix[$j][$k]=1; //wyjedynkowanie macierzy
            }
        }
        
        for($i=0;$i<count($results);$i++){ //tyle razy ile jest rezultatow
            for($j=0;$j<count($survey->getProducts());$j++){ //dla kazdego produktu
                for($k=0;$k<count($survey->getProducts());$k++){ //i jego konkurenta
                    $matrix[$j][$k]=$matrix[$j][$k]*$results[$i][$j][$k]; //przemnoz wynik z kazdej ankiety
                }
            }
        }
        
        for($j=0;$j<count($survey->getProducts());$j++){
            for($k=0;$k<count($survey->getProducts());$k++){
                $matrix[$j][$k]=pow($matrix[$j][$k],1/count($results)); //a potem te wszystkie wyniki zlogarytmuj żeby uzyskać średnią geometryczną
            }
        }
        
        $obliczone=array(); //tablica z wynikami dla poszczegolnych produktow na podstawie macierzy globalnej
        
        for($k=0;$k<count($survey->getProducts());$k++){
            $obliczone[$k]['wartosc']=1; //inicjalizacja jedynkami
        }
        
        for($j=0;$j<count($survey->getProducts());$j++){
            for($k=0;$k<count($survey->getProducts());$k++){
                $obliczone[$j]['wartosc']= $obliczone[$j]['wartosc']*$matrix[$j][$k];//obliczenie iloczynu dla danego wiersza (produktu)
            }
            $obliczone[$j]['wartosc']=pow($obliczone[$j]['wartosc'],1/count($survey->getProducts())); //logarytm i uzyskanie średniej geometrycznej dla danego produktu już globalnie
            $obliczone[$j]['produkt']=$survey->getProducts()[$j]->getName();
            $obliczone[$j]['image']=$survey->getProducts()[$j]->getImageUrl();
        }
        
        
        foreach ($obliczone as $key => $row) {
            $produkt[$key]  = $row['produkt'];
            $wartosc[$key] = $row['wartosc'];
        }

        array_multisort($wartosc, SORT_DESC, $produkt, SORT_ASC, $obliczone);

        $survey->setOverallResultArray(serialize($obliczone));
        $em->persist($survey);
        $em->flush();
        //TODO Przypisać produkt do tablicy, żeby można było posortować i nie stracić produktu
        return 0;
        //return new Response('<pre>' . print_r($obliczone, true) . '</pre>'.'<pre>' . print_r($matrix, true) . '</pre>');
    }
    
    public function calculateMatrixAfterSurvey($survey_id,$invitation_id){
        $em = $this->getDoctrine()->getManager();

        $survey = $em->getRepository('WantuchSurveyBundle:Survey')->find($survey_id);
        $invitation = $em->getRepository('WantuchSurveyBundle:Invitation')->find($invitation_id);
        
        $comparisonsArray=unserialize($survey->getPairs());
        
        $matrix=array(); //macierz dla wypełnionej ankiety
        
        $products=$survey->getProducts();
        $productsCount=count($products);
        
        for($i=0; $i<$productsCount; $i++){
            for($j=0; $j<$productsCount; $j++){
                $matrix[$i][$j]=1; //wyjedynkowanie macierzy
            }
        }
        
        $comparisons=$invitation->getComparisons(); //pobranie listy porownan od danego zaproszenia
        
        foreach($comparisons as $comparison){
            $comparison_number=$comparison->getCompNumber();
            $singleComparisonArray = $comparisonsArray[$comparison_number];
            $product1Row = $singleComparisonArray[0];
            $product1Column = $singleComparisonArray[1];
            $matrix[$product1Row][$product1Column] = $comparison->getResult();
            $matrix[$product1Column][$product1Row] = 1/($comparison->getResult());
            //$testProdukty[$product1Row]=$products[$product1Row];
        }
        
        $wynikiProdukt=array(); //tablica na wyniki dla danego produktu
        for($i=0;$i<$productsCount;$i++){
            $wynikiProdukt[$i]=1;
            for($j=0; $j<$productsCount; $j++){
                $wynikiProdukt[$i]=$wynikiProdukt[$i]*$matrix[$i][$j]; //tutaj jest mnozenie, ale co sie stalo z logarytmem
            }
        }
        
        for($i=0;$i<$productsCount;$i++){
            $wynikiProdukt[$i]=pow($wynikiProdukt[$i],1/$productsCount); //tutaj mamy juz srednia geometryczna
        }
        
        //teraz zapisanie do Result
        $result = new Result();
        $result->setInvitation($invitation);
        $resultArray=serialize($matrix);
        $result->setResultArray($resultArray);
        $result->setSurvey($survey);
        
        $em->persist($result);
        $em->flush();
        
        return $wynikiProdukt;
        //return new Response('<pre>' . print_r($matrix, true) . '</pre>'.'<pre>' . print_r($wynikiProdukt, true) . '</pre>');
    }
    
    public function makePairsArray($survey){
        if(!$survey){return false;}
        
        $pairs = array();
        
        $products=$survey->getProducts();
        $productsCount=count($products)+1;
        
        for($i=0; $i<$productsCount; $i++){
            for($j=$i+1; $j<$productsCount; $j++){
                $pair=array();
                
                $pair[0]=$i;
                $pair[1]=$j;
                
                shuffle($pair);
                $pairs[]=$pair;
            }   
        }
        shuffle($pairs);
        
        return $pairs;
    }
    
    public function compareAction($invitation_id,$survey_id, $token_hash, $compareStep,Request $request){
        $em = $this->getDoctrine()->getManager();

        $survey = $em->getRepository('WantuchSurveyBundle:Survey')->find($survey_id);
        $invitation = $em->getRepository('WantuchSurveyBundle:Invitation')->find($invitation_id);
        
        if($invitation->getToken()!=$token_hash){
            return new response("Coś próbujesz oszukać.");
        }
        
        if($invitation->getResult()!=NULL){
            return new response("Już wypełniłeś ankietę.");
        }
        
        $pairs=unserialize($survey->getPairs());
        
        $products=$survey->getProducts();
        
        $prod1arrIndex=$pairs[$compareStep-1][0];
        $product1=$products[$prod1arrIndex];
        
        $prod2arrIndex=$pairs[$compareStep-1][1];
        $product2=$products[$prod2arrIndex];
                
        $currentStep=$compareStep; //sprawdzanie na jakim etapie jestesmy - potrzebne do okreslania kolejnych linkow
        if($currentStep>1){
            $prevStep=$currentStep-1;
        }else{
            $prevStep=NULL; //tylko proforma - uzytkownik nie ma mozliwosci do powrotu
        }
        
        if($currentStep<count($pairs)){
            $nextStep=$currentStep+1;
        }else{
            $nextStep=NULL;
        }
        
        $form = $this->createFormBuilder()
            ->add('prod1value','text',array('label'=>'Prod1'))
            ->add('prod2value','text',array('label'=>'Prod2'))
            ->add('save', 'submit', array('label' => 'Nastepny+zapis'))
            ->getForm();

        $form->handleRequest($request);
        $wynikmnozenia=3/6/9*1; //do usuniecia
        $wyniktestowy=pow($wynikmnozenia,1/4); //do usuniecia
        
        //cala tablica ze wszystkimi danymi potrzebnymi do prawidlowego wyrenderowania jednego porownania
        $arrayToRender = array(
                    'product1'=>$product1, 
                    'product2'=>$product2, 
                    'currentStep'=>$currentStep,
                    'prevStep'=>$prevStep,
                    'nextStep'=>$nextStep,
                    'allSteps'=>count($pairs),
                    'form'=>$form->createView(),
                    'wyniktestowy'=>$wyniktestowy, //do usuniecia
                    'wynikmnozenia'=>$wynikmnozenia, //do usuniecia
                    'invitation'=>$invitation,
                    'token_hash'=>$invitation->getToken()
                    );
        
        
        $toRender =  $this->render('WantuchSurveyBundle:Product:compare.html.twig', $arrayToRender);
        
        if ($form->isValid()) {
            
            //4 ponizsze linijki do usuniecia - byly tylko do testow
            $tymczasowyWynik=$form->getData()["prod1value"]."/".$form->getData()["prod2value"];
            $tymczasowyWynik.=" dla porównania ".$product2->getName()."(".$prod2arrIndex.")"." vs. ".$product1->getName()."(".$prod1arrIndex.")";
            $arrayToRender['wynikmnozenia']=$tymczasowyWynik;
            $arrayToRender['form']=$form->createView();
            
            //utworz tutaj comparison, a potem przeladuj na kolejna strone
            $comparison = new Comparison();
            
            $comparison->setProduct1($product1);
            $comparison->setProduct2($product2);
            
            $comparison->setCompNumber($currentStep-1);
            $comparison->setInvitation($invitation);
            $comparison->setResult(($form->getData()["prod1value"])/($form->getData()["prod2value"]));
            
            $em->persist($comparison);
            $em->flush();
            
            
            
            //$this->calculateMatrixAfterSurvey($survey_id, $invitation_id);
            //$this->calculateOverallSurveyMatrix($survey_id);
            //render podziekowanie
            if($nextStep==NULL){
                $resultAfterSurvey = $this->calculateMatrixAfterSurvey($survey_id, $invitation_id);
                $globalResult=$this->calculateOverallSurveyMatrix($survey_id);
                
                $invitation->setFilled('T');
                $em->persist($invitation);
                $em->flush();
                
                $realResults=array();
                for($i=0;$i<count($survey->getProducts());$i++){
                    $realResults[$i]['name']=$survey->getProducts()[$i]->getName();
                    $realResults[$i]['image']=$survey->getProducts()[$i]->getImageUrl();
                    $realResults[$i]['value']=$resultAfterSurvey[$i];
                }
                
                foreach ($realResults as $key => $row) {
                    $produkt[$key]  = $row['name'];
                    $wartosc[$key] = $row['value'];
                    //$obrazek[$key] = $row['image'];
                }

                array_multisort($wartosc, SORT_DESC, $produkt, SORT_ASC, $realResults);
                
                $arrayToRenderSummary=array('invitation'=>$invitation, 
                    'resultAfterSurvey'=>$resultAfterSurvey,
                    'realResults'=> $realResults,
                    'globalResult'=>$globalResult);
                return $this->render('WantuchSurveyBundle:Product:compareSummary.html.twig', $arrayToRenderSummary);
            }
            return $this->redirect($this->generateUrl('product_compare', 
                    array(
                        'survey_id' => $survey->getId(),
                        'compareStep' => $nextStep,
                        'invitation_id'=>$invitation->getId(),
                        'token_hash'=>$invitation->getToken()
                        )));
        }
        
        
        return $toRender;
    }
}
